// This is the slider controls script 
// For this file decide either for the device tags, which are marked with //----- 
// OR for the OPC tags, which are written as normal comment tags //
// all comments with exclamation marks are required in each case //!

//all uppercase words in the file must be replaced like in the html document

function initSlider(){
    //------control for device tags
    if (!window.APTselectedElement) {
		console.error("[APT Error] No parameters sent from device to diagnosis window (window.APTselectedElement is empty)");
		return;
    }

    //!
    var actValue = 0;
    var stepSize = 1;
    var sliderStep = 1;
    var numberColumn;
    var comma; //Specifies the position to be rounded. 1 is one comma position, 0 is no comma position and -1 rounds the first digit.
    var totalRange = 0;
    
    //for tag dependent names
    var languageTexts;
    //-------for language-switchable names
    var languageTexts = {
            "T02_Gen_EXAMPLE": {
                id: "SLIDERNAME-ID",
                text: "T02_Gen_EXAMPLE"
            }
        };

    //required variables for OPC tags
    var textAdviseId = null;
    var robName = sessionStorage.getItem("apt_AT_LastSelectedRobot");
    var opc = sessionStorage.getItem("apt_" + robName + ".OpcTopic");
    var advisedId = emosWS.getNewElementId();

    //examples of variables for the OPC tags and the OPC tags themselves
    var usedSliderNumberValue = 0;
    var minValue = 0; 
    var maxValue = 0; 
    var startPositionValue = 0;
    var sliderTags = {
        usedSliderNumberTag: opc + sessionStorage.getItem("apt_" + robName + ".Tags.TimeProgSliderNumber"),
        minTagName: opc + sessionStorage.getItem("apt_" + robName + ".Tags.TimeProgSliderMin"),
        maxTagName: opc + sessionStorage.getItem("apt_" + robName + ".Tags.TimeProgSliderMax"),
        initPosTagName: opc + sessionStorage.getItem("apt_" + robName + ".Tags.TimeProgSliderInit"),
        actPosTagName: opc + sessionStorage.getItem("apt_" + robName + ".Tags.TimeProgSliderPos"), //Input Tag
        newSliderTagName: opc + sessionStorage.getItem("apt_" + robName + ".Tags.TimeProgSliderNew"),
        newSliderAckTagName: opc + sessionStorage.getItem("apt_" + robName + ".Tags.TimeProgSliderNewAck") //Input Tag
    };

    //! Check if users have right to start/use: 
    var userRightDisabledClass = "";
    var userHasRights = true;
    if (!AptCheckUserRight("Atomizer")) {
        userRightDisabledClass = "disabled";
        userHasRights = false;
    }

    //------examples for the device tags
    var type = window.APTselectedElement.type;
    var tags = window.APTselectedElement.tags;
    var number = window.APTselectedElement.number;
    var unit = window.APTselectedElement.unit;
    var minSetValue = parseFloat(window.APTselectedElement.min);
    var maxSetValue = parseFloat(window.APTselectedElement.max);
    var advisedId = emosWS.getNewElementId();
    var deviceReqValue = tags["i" + type + number +"ReqValue"];
    var initPosition = tags["o" + type + number +"ReqValue"];

//.........................................................................................................................................................................................
    function createDom() {

        //!
        var x = numberColumn;
        switch(true){
            case (x <= 3): //Placeholders must be inserted because the outer table columns cannot be wider than 65 px (61px because padding is 4px large).
                var tableWidth = '325px';
                var classes = ' class="rangeCell standardFontSize" style="width:61px"';
                var rowOne = '<td'+classes+'></td>' + '<td id="secondN"' +classes+ '></td>' + '<td'+classes+'></td>' + '<td id="thirdN"' +classes+ '></td>';
                var rowTwo = '<td'+classes+'></td>' + '<td id="second"' +classes+ '>|</td>' + '<td'+classes+'></td>' + '<td id="third"' +classes+ '>|</td>';            
                break;
            case (x == 4): //Placeholders must be inserted because the outer table columns cannot be wider than 65 px (61px because padding is 4px large).
                var tableWidth = '330px';
                var classes = ' class="rangeCell standardFontSize" style="width:61px"'; // 61 21 61 23 61 21 61
                var rowOne = '<td style="width:21px"></td>' + '<td id="secondN"' +classes+ '></td>' + '<td style="width:23px"></td>' + '<td id="thirdN"' +classes+ '></td>' + '<td style="width:21px"></td>' + '<td id="fourthN"' +classes+ '></td>';
                var rowTwo = '<td style="width:21px"></td>' + '<td id="second"' +classes+ '>|</td>' + '<td style="width:23px"></td>' + '<td id="third"' +classes+ '>|</td>' + '<td style="width:21px"></td>' + '<td id="fourth"' +classes+ '>|</td>';
                break;
            case (x == 5): //different sizes necessary due to rounding tolerances
                var tableWidth = '326px';
                var classes = ' class="rangeCell standardFontSize" style="width:61px"';
                var classes2 = ' class="rangeCell standardFontSize" style="width:62px"';
                var rowOne = '<td id="secondN"' +classes2+ '></td>' + '<td id="thirdN" class="rangeCell standardFontSize" style="width:60px"></td>' + '<td id="fourthN"' +classes2+ '></td>' + '<td id="fifthN"' +classes+ '></td>';
                var rowTwo = '<td id="second"' +classes2+ '>|</td>' + '<td id="third" class="rangeCell standardFontSize" style="width:60px">|</td>' + '<td id="fourth"' +classes2+ '>|</td>' + '<td id="fifth"' +classes+ '>|</td>'; 
                break;
            case (x == 6):
                var tableWidth = '312px';
                var classes = ' class="rangeCell standardFontSize" style="width:48px"';
                var rowOne = '<td id="secondN"' +classes+ '></td>' + '<td id="thirdN"' +classes+ '></td>' + '<td id="fourthN"' +classes+ '></td>' + '<td id="fifthN"' +classes+ '></td>' + '<td id="sixthN"' +classes+ '></td>';
                var rowTwo = '<td id="second"' +classes+ '>|</td>' + '<td id="third"' +classes+ '>|</td>' + '<td id="fourth"' +classes+ '>|</td>' + '<td id="fifth"' +classes+ '>|</td>' + '<td id="sixth"' +classes+ '>|</td>'; 
                break;
            case (x == 7):
                var tableWidth = '301px';
                var classes = ' class="rangeCell standardFontSize" style="width:39px"';
                var classes1 = ' class="rangeCell standardFontSize" style="width:38px"';
                var classes2 = ' class="rangeCell standardFontSize" style="width:41px"';
                var rowOne = '<td id="secondN"' +classes+ '></td>' + '<td id="thirdN"' +classes1+ '></td>' + '<td id="fourthN"' +classes2+ '></td>' + '<td id="fifthN"' +classes1+ '></td>' + '<td id="sixthN"' +classes+ '></td>' + '<td id="seventhN"' +classes+ '></td>';
                var rowTwo = '<td id="second"' +classes+ '>|</td>' + '<td id="third"' +classes+ '>|</td>' + '<td id="fourth"' +classes2+ '>|</td>' + '<td id="fifth"' +classes+ '>|</td>' + '<td id="sixth"' +classes+ '>|</td>' + '<td id="seventh"' +classes+ '>|</td>'; 
                break;
            case (x == 8):
                var tableWidth = '297px';
                var classes = ' class="rangeCell standardFontSize" style="width:33px"';
                var rowOne = '<td id="secondN"' +classes+ '></td>' + '<td id="thirdN"' +classes+ '></td>' + '<td id="fourthN"' +classes+ '></td>' + '<td id="fifthN"' +classes+ '></td>' + '<td id="sixthN"' +classes+ '></td>' + '<td id="seventhN"' +classes+ '></td>' + '<td id="eighthN"' +classes+ '></td>';
                var rowTwo = '<td id="second"' +classes+ '>|</td>' + '<td id="third"' +classes+ '>|</td>' + '<td id="fourth"' +classes+ '>|</td>' + '<td id="fifth"' +classes+ '>|</td>' + '<td id="sixth"' +classes+ '>|</td>' + '<td id="seventh"' +classes+ '>|</td>' + '<td id="eighth"' +classes+ '>|</td>';
                break;
            case (x == 9):
                var tableWidth = '290px';
                var classes = ' class="rangeCell standardFontSize" style="width:29px"';
                var classes2 = ' class="rangeCell standardFontSize" style="width:28px"';
                var rowOne = '<td id="secondN"' +classes+ '></td>' + '<td id="thirdN"' +classes2+ '></td>' + '<td id="fourthN"' +classes2+ '></td>' + '<td id="fifthN"' +classes+ '></td>' + '<td id="sixthN"' +classes+ '></td>' + '<td id="seventhN"' +classes2+ '></td>' + '<td id="eighthN"' +classes+ '></td>' + '<td id="ninthN"' +classes+ '></td>';
                var rowTwo = '<td id="second"' +classes+ '>|</td>' + '<td id="third"' +classes2+ '>|</td>' + '<td id="fourth"' +classes2+ '>|</td>' + '<td id="fifth"' +classes+ '>|</td>' + '<td id="sixth"' +classes+ '>|</td>' + '<td id="seventh"' +classes2+ '>|</td>' + '<td id="eighth"' +classes+ '>|</td>' + '<td id="ninth"' +classes+ '>|</td>';
                break;
            case (x >= 10):
                var tableWidth = '289px';
                var classes = ' class="rangeCell standardFontSize" style="width:25px"';
                var rowOne = '<td id="secondN"' +classes+ '></td>' + '<td id="thirdN"' +classes+ '></td>' + '<td id="fourthN"' +classes+ '></td>' + '<td id="fifthN"' +classes+ '></td>' + '<td id="sixthN"' +classes+ '></td>' + '<td id="seventhN"' +classes+ '></td>' + '<td id="eighthN"' +classes+ '></td>' + '<td id="ninthN"' +classes+ '></td>' + '<td id="tenthN"' +classes+ '></td>';
                var rowTwo = '<td id="second"' +classes+ '>|</td>' + '<td id="third"' +classes+ '>|</td>' + '<td id="fourth"' +classes+ '>|</td>' + '<td id="fifth"' +classes+ '>|</td>' + '<td id="sixth"' +classes+ '>|</td>' + '<td id="seventh"' +classes+ '>|</td>' + '<td id="eighth"' +classes+ '>|</td>' + '<td id="ninth"' +classes+ '>|</td>' + '<td id="tenth"' +classes+ '>|</td>';
                break;
        }
        var createTable = '<table id="rangeTable" style="' + tableWidth + '" style="text-align:center">' + 
                    '<tr>' + '<td id="firstN"' +classes+ '></td>' + rowOne + '</tr>' +
                    '<tr>' + '<td id="first"' +classes+ '>|</td>' + rowTwo + '</tr>' + '</table>';
    
        $('#TABLE-ID').empty();
        $('#TABLE-ID').append(createTable);

        if (userHasRights) { //if the user has the rights to use the slider, the class "disabled" will be removed
			$("#MINUSBUTTON-ID").removeClass("disabled");
            $("#PLUSBUTTON-ID").removeClass("disabled");
            $("#SLIDER-ID").removeClass("disabled");
            $("#ACTVALUE-ID").removeClass("disabled");
        }
        
        //------for the device tags a different css code is used, there is a field for the unit
        $("#UNIT-ID").text(unit);
    }


    function eventHandler(){

        $('#SLIDER-ID').on('touchend mouseup', function (event) {
            var val = event.currentTarget.value;

            //example for OPC tags
            emosWS.poke(sliderTags.actPosTagName, val);
            //------example for device tags
            emosWS.poke(deviceReqValue, val);

            actValue = val;
            $("#ACTVALUE-ID").text(val);
        });

        $("#MINUSBUTTON-ID").click(function (){
            actValue = parseFloat(actValue);
            stepSize = parseFloat(stepSize);
            if((actValue - stepSize) >= minSetValue){
                actValue = actValue - stepSize;

                //------ only needed for big numbers (device values)
                actValue = roundActValue(actValue, comma);

                $("#ACTVALUE-ID").text(actValue);

                //example for OPC tags
                emosWS.poke(sliderTags.actPosTagName, actValue);
                //------example for device tags
                emosWS.poke(deviceReqValue, actValue);

                document.getElementById('SLIDER-ID').value = actValue;
            }
        });

        $("#PLUSBUTTON-ID").click(function (){
            actValue = parseFloat(actValue);
            stepSize = parseFloat(stepSize);
            if((actValue + stepSize) <= maxSetValue){
                actValue = actValue + stepSize;

                //------ only needed for big numbers (device values)
                actValue = roundActValue(actValue, comma);

                $("#ACTVALUE-ID").text(actValue);

                //example for OPC tags
                emosWS.poke(sliderTags.actPosTagName, actValue);
                //------example for device tags
                emosWS.poke(deviceReqValue, actValue);

                document.getElementById('SLIDER-ID').value = actValue;
            }
        });

        //! Numpad actions
        $('#ACTVALUE-ID').click(function(){
            $("#ACTVALUE-ID").text("");
            $("#EDITFIELD-ID").removeClass("hide");
        });
        $('#NUMPADDOT-ID').click(function(){
            var val = $('#ACTVALUE-ID').text() + ".";
            $('#ACTVALUE-ID').text(val);
        });
        $('#NUMPADCLEAR-ID').click(function(){
            $('#ACTVALUE-ID').text("");
        });
        $('#NUMPADCANCEL-ID').click(function(){
            $('#ACTVALUE-ID').text(actValue);
            $('#EDITFIELD-ID').addClass('hide');
        });
        $('#NUMPADACCEPT-ID').click(function () {
            var text = $('#ACTVALUE-ID').text();
            if(text == "" | text == "."){
                $("#ACTVALUE-ID").text(actValue);
            }
            else if((text = parseFloat(text)) < minSetValue){
                $("#ACTVALUE-ID").text(minSetValue);
                actValue = minSetValue;
            }
            else if((text = parseFloat(text)) > maxSetValue){
                $("#ACTVALUE-ID").text(maxSetValue);
                actValue = maxSetValue;
            }
            else{
                actValue = text;
            }

            //example for OPC tags
            emosWS.poke(sliderTags.actPosTagName, actValue);
            //------example for device tags
            emosWS.poke(deviceReqValue, actValue);

            document.getElementById('SLIDER-ID').value = actValue;
            $('#EDITFIELD-ID').addClass('hide');
        });
    }

    function dataHandler(){
        //......example for device tags
        emosWS.advise(deviceReqValueMan, function(msg) {
            var val = msg.value;
            document.getElementById('SLIDER-ID').value = val;
            $("#ACTVALUE-ID").text(val);
            actValue = val
        }).setId(advisedId);

        //example for OPC tags
            //all tags get an advised id
        Object.keys(sliderTags).forEach(function(tag){
            emosWS.advise(sliderTags[tag]).setId(advisedId);
        });
            //this tag is used to build or update the slider (OPC)
        emosWS.advise(sliderTags.usedSliderNumberTag, function (msg) {
            //in case the dropdowns are selected
            if(msg.value !== "0"){
                $("#MINUSBUTTON-ID").removeClass("hide");
                $("#PLUSBUTTON-ID").removeClass("hide");
                $("#SLIDER-ID").removeClass("hide");
                $("#ACTVALUE-ID").removeClass("hide");
                $("#TABLE-ID").removeClass("hide");
                $("#SLIDERNAME-ID").removeClass("hide");
                
                usedSliderNumberValue = msg.value;

                emosWS.advise(sliderTags.minTagName, function (msg) {
                    minValue = msg.value;
                }).setId(advisedId);
        
                emosWS.advise(sliderTags.maxTagName, function (msg) {
                    maxValue = msg.value;
                }).setId(advisedId);
        
                emosWS.advise(sliderTags.initPosTagName, function (msg) {
                    startPositionValue = msg.value;
                }).setId(advisedId);

                languageTexts = translateSliderHeader();
                languageHandler(languageTexts);
                range();
                createDom();
                setSliderValues();
            }
            else{
                $("#MINUSBUTTON-ID").addClass('hide');
                $("#PLUSBUTTON-ID").addClass('hide');
                $("#SLIDER-ID").addClass('hide');
                $("#ACTVALUE-ID").addClass('hide');
                $("#TABLE-ID").addClass('hide');
                $("#SLIDERNAME-ID").addClass('hide');
            }
        }).setId(advisedId);
            //this tag is used to update the slider (OPC)
        emosWS.advise(sliderTags.newSliderTagName, function (msg) {
            // New slider
            if(msg.value !== "0"){

                languageTexts = translateSliderHeader();
                languageHandler(languageTexts);
                range();
                createDom();
                setSliderValues();
                emosWS.poke(sliderTags.newSliderAckTagName, 1);
            }
            else{
                // Reset the acknowledge tag, we have a new slider already confirmed
                emosWS.poke(sliderTags.newSliderAckTagName, 0);
            }
        }).setId(advisedId);
    }
    
    function range() {
        //variable from OPC
            //determines the total width of the slider
        if(minValue == 0){
            maxValue = parseInt(maxValue);
            totalRange = maxValue + 1;
        }
        else{
            minValue = parseInt(minValue);
            totalRange = maxValue - minValue + 1;
        }

        //variable from Device
            //determines the total width of the slider
        if(minSetValue == 0){
            totalRange = maxSetValue;
        }
        else{
            totalRange = (minSetValue *(-1)) + maxSetValue;
        }
            //determines the number of colums for the device table
        var x = totalRange;
        if (x % 5 == 0){
            numberColumn = 6;
        }
        else if (x % 4 == 0)  {
            numberColumn = 5;
        }  
        else if (x % 3 == 0){
            numberColumn = 4;
        }
        else if (x % 2 == 0){
            numberColumn = 3;
        }
        else{
            numberColumn = 5;
        }
    }


    function setSliderValues() {
        //example for OPC
            //determines the values above the slider (in the table)
        $("#firstN").text(minValue);

        minValue = parseInt(minValue);
        var numberTwo = minValue + 1;
        $("#secondN").text(numberTwo);

        var numberThree = minValue + 2 -1 +1;
        $("#thirdN").text(numberThree);

        var numberFour = minValue + 3;
        $("#fourthN").text(numberFour);

        var numberFife = minValue + 4;
        $("#fifthN").text(numberFife);
        
        var numberSix = minValue + 5;
        $("#sixthN").text(numberSix);

        var numberSeven = minValue + 6;
        $("#seventhN").text(numberSeven);

        var numberEight = minValue + 7;
        $("#eighthN").text(numberEight);

        var numberNine = minValue + 8;
        $("#ninthN").text(numberNine);

        var numberTen = minValue + 9;
        $("#tenthN").text(numberTen);


        //......defines the step sizes and the position of the first rounded number based on the total length
            //for OPC not needed because stepsize is always 1 and has only integer
        var x = totalRange;
            //Depending on the total width, the step size and the point to be rounded are determined.
        switch(true){
            case (0 <= x && x <= 9):
                sliderStep = 0.1;
                stepSize = 0.1;
                comma = 1;
                break;
            case (10 <= x && x <= 499):
                stepSize = 1;
                comma = 0;
                break;
            case (500 <= x && x <= 4999):
                stepSize = 10;
                comma = (-1);
                break;
            case (5000 <= x && x <= 9999):
                stepSize = 100;
                comma = (-2);
                break;
            case (x >= 10000):
                stepSize = 1000;
                comma = (-2);
                break;
        }

        //......determines the values above the slider (in the table) for device
        $("#firstND").text(minSetValue);

        var numberTwo = minSetValue + ((totalRange/(numberColumn-1))*1);
        var val2 = roundActValue(numberTwo, comma);
        $("#secondND").text(val2);

        var numberThree = minSetValue + ((totalRange/(numberColumn-1))*2);
        var val3 = roundActValue(numberThree, comma);
        $("#thirdND").text(val3);
        if(numberColumn==3){$("#thirdND").text(maxSetValue);}

        var numberFour = minSetValue + ((totalRange/(numberColumn-1))*3);
        var val4 = roundActValue(numberFour, comma);
        $("#fourthND").text(val4);
        if(numberColumn==4){$("#fourthND").text(maxSetValue);}

        var numberFife = minSetValue + ((totalRange/(numberColumn-1))*4);
        var val5 = roundActValue(numberFife, comma);
        $("#fifthND").text(val5);
        if(numberColumn==5){$("#fifthND").text(maxSetValue);}
        
        var numberSix = minSetValue + ((totalRange/(numberColumn-1))*5);
        var val6 = roundActValue(numberSix, comma);
        $("#sixthND").text(val6);
        if(numberColumn==6){$("#sixthND").text(maxSetValue);}

        var numberSeven = minSetValue + ((totalRange/(numberColumn-1))*6);
        var val7 = roundActValue(numberSeven, comma);
        $("#seventhND").text(val7);
        if(numberColumn==7){$("#seventhND").text(maxSetValue);}

        var numberEight = minSetValue + ((totalRange/(numberColumn-1))*7);
        var val8 = roundActValue(numberEight, comma);
        $("#eighthND").text(val8);
        if(numberColumn==8){$("#eighthND").text(maxSetValue);}

        var numberNine = minSetValue + ((totalRange/(numberColumn-1))*8);
        var val9 = roundActValue(numberNine, comma);
        $("#ninthND").text(val9);
        if(numberColumn==9){$("#ninthND").text(maxSetValue);}

        var numberTen = minSetValue + ((totalRange/(numberColumn-1))*9);
        var val10 = roundActValue(numberTen, comma);
        $("#tenthND").text(val10);
        if(numberColumn==10){$("#tenthND").text(maxSetValue);}

        //......minimum and maximum are passed to the slider, device
        document.getElementById('SLIDER-ID').min = minSetValue;
        document.getElementById('SLIDER-ID').max = maxSetValue;
        document.getElementById('SLIDER-ID').step = sliderStep;
        

        //minimum and maximum are passed to the slider, OPC
        document.getElementById('SLIDER-ID').min = minValue;
        document.getElementById('SLIDER-ID').max = maxValue;
        document.getElementById('SLIDER-ID').value = startPositionValue;
        document.getElementById('SLIDER-ID').step = stepSize;
            //Displays the start position in the input field.
        $("#ACTVALUE-ID").text(startPositionValue);
        actValue = startPositionValue;
    }

    //whole function is only required for OPC (depending on the dropdown menus)
    function translateSliderHeader(){
        var textIdPrefix = "T02_TP_Slider"; // Prefix to build the textId
        var textIdPostfix = "_AB"; // Append to textId if it has AB process
        var textId = textIdPrefix + usedSliderNumberValue;

        emosWS.unadvise(textAdviseId);
        textAdviseId = emosWS.getNewElementId();
        emosWS.sendAdviseText(textId, "name", function(msg){
            $('#SLIDERNAME-ID').text(msg.value);
        }).setId(textAdviseId);
    }

    //the other functions are called at OPC by a change of the usedSlider tag
    dataHandler(); 
    eventHandler();

    //......device
    languageHandler(languageTexts);
    range();
    createDom();
    setSliderValues();
    dataHandler(); 
    eventHandler();
}

//!adds the number strings and displays them in the input field
function inputNumber(number){
    var val = $('#ACTVALUE-ID').text() + number;
    $('#ACTVALUE-ID').text(val);  
}

//......rounds the value to the specified position
function roundActValue(value, comma) {
    value = parseFloat(value);
    if (!value){
        return 0;
    } 
    comma = parseInt(comma);
    if (!comma){
        comma=0;
    } 
    var factor = Math.pow(10,comma);
    return Math.round(value * factor) / factor;
}
